#if (UNITY_WEBGL || MINIGAME_SUBPLATFORM_KUAISHOU) && SEEG_PF_KS

using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using UnityEngine;

namespace ZhiSe.Editor
{
    public class SeegKSBuild
    {
        public static async Task afterBuildTemplate(JObject cfg)
        {
            var delayTime = 3000;
            if (cfg.ContainsKey("ksBuildTime"))
            {
                delayTime = (int)cfg["ksBuildTime"] * 1000;
            }
            await Task.Delay(delayTime); 
            var ksPath = Path.Combine(Path.GetDirectoryName(SeegBuild.OutputPath)!, "miniPlay", "game.js") ;
            if (!File.Exists(ksPath))
            { 
                Debug.LogWarning("[SEEG] 项目未集成快手SDK或快手小游戏未转换完");
                return; 
            }
            var lines = File.ReadAllLines(ksPath).ToList();
            // 直接用字符串包含判断，兼容所有缩进
            var inserted = false;
            for (var i = 0; i < lines.Count; i++)
            {
                if (!lines[i].Contains("createUnityInstance")) continue;
                var insertLine = i + 2;
                // 检查下一行是否已经插入过
                if (insertLine < lines.Count && lines[insertLine].Replace(" ", "").Contains("GameGlobal.unityInstance"))
                {
                    break;
                }
                lines[i + 1] = "    .then((instance) => {";
                lines.Insert(insertLine, $"GameGlobal.unityInstance = unityInstance;\nwindow.zs = window.zs || {{}};\nwindow.zs.gameConfig = {cfg.ToString()}");
                inserted = true;
                break;
            }
            if (inserted)
            {
                await File.WriteAllLinesAsync(ksPath, lines);
                Debug.Log("[SEEG] 快手模板修改完毕");
            }
            else
            {
                Debug.Log("[SEEG] 快手模板已修改，无需再次修改");
            }
        }
    }
}
#endif